﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using HeartLess.Core;
using Microsoft.Xna.Framework;

namespace HeartLess.Managers
{
    public static class ShaderManager
    {
        private static Dictionary<IShaderDrawer, RenderTarget2D> _shaders;

        static ShaderManager()
        {
            _shaders = new Dictionary<IShaderDrawer, RenderTarget2D>();
        }

        public static void addShaderDrawer(IShaderDrawer shaderDrawer)
        {
            RenderTarget2D renderTarget = new RenderTarget2D(HeartlessGame.Game.GraphicsDevice,
                                                        Screen.WINDOW_WIDTH, Screen.WINDOW_HEIGHT);
            _shaders.Add(shaderDrawer, renderTarget);
        }

        public static void removeShaderDrawer(IShaderDrawer shaderDrawer)
        {
            _shaders.Remove(shaderDrawer);
        }

        public static void clearShaderDrawers()
        {
            _shaders.Clear();
        }

        public static void DrawShaders(SpriteBatch spriteBatch)
        {
            foreach (KeyValuePair<IShaderDrawer, RenderTarget2D> shader in _shaders)
            {
                IShaderDrawer shaderDrawer = shader.Key;
                RenderTarget2D renderTarget = shader.Value;

                HeartlessGame.Game.GraphicsDevice.SetRenderTarget(renderTarget);
                HeartlessGame.Game.GraphicsDevice.Clear(Color.Transparent);

                spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.NonPremultiplied);
                //spriteBatch.Begin();
                shaderDrawer.DrawShader(spriteBatch, renderTarget);
                spriteBatch.End();
            }

            HeartlessGame.Game.GraphicsDevice.SetRenderTarget(null);
        }

        public interface IShaderDrawer
        {
            void DrawShader(SpriteBatch spriteBatch, RenderTarget2D renderTarget);
        }

    }
}
